package com.twu.biblioteca;

import java.util.ArrayList;

/**
 * Created by larahy on 17/04/2014.
 */
public class Librarian {
    Library library;
    ArrayList<LedgerItem> ledgerItems;
    ArrayList<User> users;
    User currentUser;

    public Librarian(Library libName) {
        library = libName;
        ledgerItems = new ArrayList<LedgerItem>();
        users = new ArrayList<User>();
    }

    public String checkoutRentable(String title, User user) {
        Rentable rentable = library.findByTitle(title);

        if(library.available(title)) {
            ledgerItems.add(new LedgerItem(rentable, user));
            try {
                library.checkout(title);
            } catch(Exception e) {};

            return "Thank you, enjoy the book!";
        } else {
            return "I'm afraid that title is not available";
        }
    }

    public LedgerItem findByRentable(Rentable aRentable) {
        for(LedgerItem ledgerItem: ledgerItems) {
            if(ledgerItem.rentable.equals(aRentable)) {
                return ledgerItem;
            }
        }
        return null;
    }

    public String returnRentable(String title, User user) {
        Rentable rentable = library.findByTitle(title);
        LedgerItem ledgerItem = findByRentable(rentable);
        if(library.exists(title)) {
            ledgerItems.remove(ledgerItem);
            try {
                library.returnItem(title);
            } catch (Exception e) {};
            return "Thank you for returning the book.";
        } else {
            return "That is not a valid item to return.";
        }
    }

    public String viewLedgerItems() {
        String result = "";
        for(LedgerItem ledgerItem: ledgerItems) {
           result = ledgerItem.rentable.title + ": " + ledgerItem.user.name;
        }
        return result;
    }

    void login(User aUser) throws Exception {
        for (User user : users) {
            if (aUser.password.equals(user.password) && aUser.membershipNo.equals(user.membershipNo)) {
                aUser.loggedIn = true;
                currentUser = user;
                user.loggedIn = true;
                return;
            }
            throw new Exception("Invalid input, please try again");
        }
    }


}
